import {
  login,
  logout,
  getUserInfo,
  getMessage,
  getContentByMsgId,
  hasRead,
  removeReaded,
  restoreTrash,
  getUnreadCount
} from '@/api/user'
import { getData } from '@/api/data'
import { setToken, getToken, setUserName, getUserName } from '@/libs/util'
import { get } from 'https';

export default {
  state: {
    userName: getUserName(),
    userId: '',
    avatorImgPath: '',
    token: getToken(),
    access: '',
    hasGetInfo: false,
    unreadCount: 0,
    unreaDrawing: 0,
    subDrawing: 0,
    messageUnreadList: [],
    messageReadedList: [],
    messageTrashList: [],
    messageContentStore: {},
    meunArrList:[]
  },
  mutations: {
    setAvator(state, avatorPath) {
      state.avatorImgPath = avatorPath
    },
    setUserId(state, id) {
      state.userId = id
    },
    setUserName(state, name) {
      state.userName = name;
      setUserName(name);
    },
    setAccess(state, access) {
      state.access = access
      // state.access = [1,2,3,4,'4-1',5,6,7]
    },
    SetMeunArrList(state, meunArrList) {
      state.meunArrList = meunArrList;
    },
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    setHasGetInfo(state, status) {
      state.hasGetInfo = status
    },
    setMessageCount(state, count) {
      state.unreadCount = count
    },
    setMessageDrawingCount(state, count) {
      state.unreaDrawing = count
    },
    setMessagesub(state, count) {
      state.subDrawing = count
    },
    setMessageUnreadList(state, list) {
      state.messageUnreadList = list
    },
    setMessageReadedList(state, list) {
      state.messageReadedList = list
    },
    setMessageTrashList(state, list) {
      state.messageTrashList = list
    },
    updateMessageContentStore(state, { msg_id, content }) {
      state.messageContentStore[msg_id] = content
    },
    moveMsg(state, { from, to, msg_id }) {
      const index = state[from].findIndex(_ => _.msg_id === msg_id)
      const msgItem = state[from].splice(index, 1)[0]
      msgItem.loading = false
      state[to].unshift(msgItem)
    }
  },
  getters: {
    messageUnreadCount: state => state.messageUnreadList.length,
    messageReadedCount: state => state.messageReadedList.length,
    messageTrashCount: state => state.messageTrashList.length
  },
  actions: {
    // 登录
    handleLogin({ commit }, { userName, password }) {
      userName = userName.trim()
      return new Promise((resolve, reject) => {
        login({
          userName,
          password
        }).then(res => {
          if (res.data.code !== 0) {
            resolve(res.data.msg)
          } else {
            commit('setToken', res.data.data.token);
            commit('setUserName', res.data.data.username);
            getData(`/main.index/grade`).then(res => {
              if (res.data.code === 0) {
                window.localStorage.setItem('permission', JSON.stringify(res.data.data))
              }
            })
            resolve()
          }
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut({ state, commit }) {
      return new Promise((resolve, reject) => {
        //   logout(state.token).then(res => {
        //     commit('setToken', '')
        //     commit('setAccess', [])
        //     window.localStorage.removeItem('permission')
        //     resolve()
        //   }).catch(err => {
        //     reject(err)
        //   })
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        commit('setToken', '')
        commit('setAccess', [])
        sessionStorage.setItem("meunArrList", '[]');
        commit('SetMeunArrList', '')
        resolve()
      })
    },
    // 获取用户相关信息
    getUserInfo({ state, commit }) {
      return new Promise((resolve, reject) => {
        try {
          getData(`/main.index/getAcl`).then(res => {
            if (res.data.code === 0) {
              const data = res.data;
              if (data.data.length === 0) {
                let access = ['admin'];
                data.access = access;
                commit('setAccess', access);
                resolve(data);
              } else {
                if (!data.data[0]) {
                  Notice.warning({
                    title: '您还未设置权限，请联系管理员设置权限！！'
                  })
                  setToken('');
                  setTimeout(() => {
                    window.location.reload()
                  }, 2000)
                  return;
                } else {
                  let accessArr = [];
                  sessionStorage.setItem('meunArrList', JSON.stringify(data.data[0]));
                  commit('SetMeunArrList', data.data[0]);
                  data.data[0].map(item => {
                    accessArr.push(item.code);
                    if (item.child.length) {
                      item.child.map(item => {
                        accessArr.push(item.code);
                      })
                    }
                  })
                  commit('setAccess', accessArr);
                  data.access = accessArr;
                  resolve(data);
                }
              };
            }else{
              resolve(false);
            }
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    },
    // 此方法用来获取未读消息条数，接口只返回数值，不返回消息列表
    getUnreadMessageCount({ state, commit }) {
      // 关于消息提示的说明：消息提示不是及时的提示，在router/index.js下每次变换路由会请求一次未处理的消息数//这里是第一次的数据设置
      getData(`/main.notic/menu`).then(res => {
        const { data } = res.data;
        // commit('setMessageCount', data.store_invite);//邀请信息
        // commit('setMessageDrawingCount', data.store_drawing);//审批信息
        // commit('setMessagesub', data.site_drawing);//分站审批
      })
    },
    // 获取消息列表，其中包含未读、已读、回收站三个列表
    getMessageList({ state, commit }) {
      return new Promise((resolve, reject) => {
        getMessage().then(res => {
          const { unread, readed, trash } = res.data
          commit('setMessageUnreadList', unread.sort((a, b) => new Date(b.create_time) - new Date(a.create_time)))
          commit('setMessageReadedList', readed.map(_ => {
            _.loading = false
            return _
          }).sort((a, b) => new Date(b.create_time) - new Date(a.create_time)))
          commit('setMessageTrashList', trash.map(_ => {
            _.loading = false
            return _
          }).sort((a, b) => new Date(b.create_time) - new Date(a.create_time)))
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 根据当前点击的消息的id获取内容
    getContentByMsgId({ state, commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        let contentItem = state.messageContentStore[msg_id]
        if (contentItem) {
          resolve(contentItem)
        } else {
          getContentByMsgId(msg_id).then(res => {
            const content = res.data
            commit('updateMessageContentStore', { msg_id, content })
            resolve(content)
          })
        }
      })
    },
    // 把一个未读消息标记为已读
    hasRead({ state, commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        hasRead(msg_id).then(() => {
          commit('moveMsg', {
            from: 'messageUnreadList',
            to: 'messageReadedList',
            msg_id
          })
          commit('setMessageCount', state.unreadCount - 1)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 删除一个已读消息到回收站
    removeReaded({ commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        removeReaded(msg_id).then(() => {
          commit('moveMsg', {
            from: 'messageReadedList',
            to: 'messageTrashList',
            msg_id
          })
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 还原一个已删除消息到已读消息
    restoreTrash({ commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        restoreTrash(msg_id).then(() => {
          commit('moveMsg', {
            from: 'messageTrashList',
            to: 'messageReadedList',
            msg_id
          })
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}
